
import pymysql
print("start")
conn = pymysql.connect(host='127.0.0.1', port=3308, user='root', database='world', password='123456', charset='utf8')
cursor = conn.cursor()

cursor.execute("select @@version")
version = cursor.fetchone()

if version:
    print('Running version: ', version)
else:
    print('Not connected.')
    

#cursor = conn.cursor()
#sql = "SELECT * FROM city WHERE ID > %s" % (1)
sql = 'SELECT * FROM city'
print(sql)


try:
   # 执行SQL语句
   cursor.execute(sql)
   results = cursor.fetchone()
   print("AA")
   print(results)
   print("ID=%d,Name=%s,Population=%d" %(results[0], results[1], results[4]))
   cursor.execute(sql)
   results = cursor.fetchall()
   for row in results:
      ID = row[0]
      Name = row[1]
      Population = row[4]
      # 打印结果
      print("ID = {},Name = {}, Population = {}".format(ID, Name, Population))
except:
   print("Error: unable to fetch data ee")
   

insert_sql = "INSERT INTO city(Name, CountryCode, District, Population) VALUES ('%s', '%s', '%s', %d )"%('neimg', 'CHN', 'F', 1112800)
print(insert_sql)

try:
   # Execute the SQL command
   cursor.execute(insert_sql)
   # Commit your changes in the database
   conn.commit()
except:
   # Rollback in case there is any error
   print("Error: unable to insert data")
   conn.rollback()
   
conn.close()


#insert_sql = 'insert into %s (%s) values (%s)' % (table_name, keys, values_params)


print(sql)


print("end")

